import { TipError } from './tip';
import invokeWechatMiniPay, { invokeWechatMiniShopPay } from './pay/wechat_mini';
import invokeWechatPay from './pay/wechat';
import invokeAliPay from './pay/alipay';
import invokeToutiaoPay from './pay/toutiao';
import { getBrowserDebug, getLocationValue } from '@biztools/info';
import logger from './logger';

// 三个环境的 ua
// 微信网页：Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 MicroMessenger/7.0.3(0x17000321) NetType/WIFI Language/zh_CN miniProgram
// 微信小程序：Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 MicroMessenger/7.0.3(0x17000321) NetType/WIFI Language/zh_CN
// 支付宝网页：Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 ChannelId(68) NebulaSDK/1.8.100112 Nebula PSDType(1) AlipayDefined(nt:WIFI,ws:375|748|3.0) AliApp(AP/10.1.55.6001) AlipayClient/10.1.55.6001 Alipay Language/zh-Hans
// 抖音小程序：Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 aweme_12.8.0 JsSdk/2.0 NetType/4G Channel/App Store ByteLocale/zh Region/CN AppTheme/dark ByteFullLocale/zh-Hans-CN Aweme/12.8.0 Mobile ToutiaoMicroApp/1.79.1.2

// 区别
// 微信网页：MicroMessenger/7.0.3(0x17000321) NetType/WIFI Language/zh_CN miniProgram
// 微信小程序：MicroMessenger/7.0.3(0x17000321) NetType/WIFI Language/zh_CN
// 支付宝网页：ChannelId(68) NebulaSDK/1.8.100112 Nebula PSDType(1) AlipayDefined(nt:WIFI,ws:375|748|3.0) AliApp(AP/10.1.55.6001) AlipayClient/10.1.55.6001 Alipay Language/zh-Hans
// 头条小程序：ToutiaoMicroApp

// 环境相关方法
const wx = window.wx;
const ap = window.Ali;
/**
 * 环境标识方法，返回当前所处的浏览器环境
 * @returns {String} target 取值：'wechat' 'wechat_mini' 'alipay'
 */
export const envTarget = () => {
    const ua = window.navigator.userAgent;
    if (/MicroMessenger/.test(ua)) {
        // 兼容开发环境下，开发工具的 ua
        return /miniprogram|miniprogramhtmlwebview|miniProgram/.test(ua) || window.__wxjs_environment === 'miniprogram' ? 'mina' : 'wechat';
    }
    if (/AlipayClient/.test(ua)) {
        // return /MiniProgram/.test(ua) ? 'aliminiapp' : 'alipay';
        return 'alipay';
    }
    if (/toutiaomicroapp/.test(ua.toLocaleLowerCase())) {
        // return /MiniProgram/.test(ua) ? 'aliminiapp' : 'alipay';
        return 'toutiao';
    }
    return getBrowserDebug() ? 'wechat' : 'browser';
};

/**
 * 平台真实性判断
 */
export const platformTruth = () => {
    const isWechat = /wechat/.test(envTarget());
    const isWechatMini = /mina/.test(envTarget());
    const isAlipay = /alipay/.test(envTarget());
    const isAlipayMini = /MiniProgram/.test(window.navigator.userAgent);
    const isToutiaoMini = /toutiao/.test(envTarget());
    const isTruthEnv = isWechat || isAlipay || isWechatMini || isAlipayMini || isToutiaoMini; // 是否是有效的业务环境
    return {
        isWechat,
        isWechatMini,
        isAlipay,
        isTruthEnv,
        isAlipayMini,
        isToutiaoMini,
    };
};

/**
 * 根据不同获取当前的位置信息，微信环境下，确保提前执行 wx.config 注册 ‘getLocation’
 * @returns {Object} location 位置信息
 */
export const getLocation = () => {
    const { isWechat, isWechatMini, isAlipay, isToutiaoMini } = platformTruth();
    logger.warn('当前是否是头条小程序', isToutiaoMini);
    return new Promise((resolve, reject) => {
        if (isWechat || isWechatMini) {
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    resolve({latitude, longitude});
                },
                fail: function (res) {
                    reject(false);
                },
                complete: function (res) {
                    console.info('complete' + res);
                },
                cancel: function (res) {
                    console.warn('cancel' + res);
                },
                trigger: function (res) {
                    console.warn('trigger' + res);
                }
            });
        } else if (isAlipay) {
            ap.geolocation.getCurrentPosition((res) => {
                const { error, errorMessage, latitude, longitude } = res;
                if (error) {
                    reject(errorMessage);
                } else {
                    resolve({latitude, longitude});
                }
            });
        } else if (isToutiaoMini) {
            const info = getLocationValue();
            info ? resolve(info) : resolve(false);
        } else {
            TipError('无法获取地址');
            resolve(false);
        }
    });
};

/**
 * 执行扫码操作，微信环境下，确保提前执行 wx.config 注册 ‘scanQRCode’
 * @returns {String} uri 返回扫码的结果
 */
export const scanQRCode = () => {
    const { isWechat, isAlipay } = platformTruth();
    return new Promise((resolve, reject) => {
        if (isWechat) {
            wx && wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    const { resultStr } = res;
                    resolve(resultStr);
                },
            });
        } else if (isAlipay) {
            ap && ap.scan({
                type: 'qr',
            }, (res) => {
                const { barCode, qrCode, cardNumber } = res;
                resolve(barCode || qrCode || cardNumber);
            });
        } else {
            TipError('无法执行扫码');
        }
    });
};

/**
 * 自动执行充值支付，根据平台自行执行
 * @param {Object} prepayRes 预支付订单
 * @param {String} orderNumber 订单号
 * @param {Function} callback 回调函数
 */
export const autoRechargePayment = (prepayRes, orderNumber, callback) => {
    const { isWechat, isWechatMini, isAlipay, isToutiaoMini } = platformTruth();
    if (isWechatMini) {
        const backUrl = encodeURIComponent(`${window.location.origin}/sole/member/pay-result`);
        // 小程序环境，走小程序支付流程
        invokeWechatMiniPay(prepayRes, orderNumber, backUrl);
        return;
    }
    if (isWechat) {
        // 微信网页，走微信支付
        invokeWechatPay(prepayRes, orderNumber, callback);
        return;
    }
    if (isAlipay) {
        invokeAliPay(prepayRes, orderNumber, callback);
        return;
    }
    if (isToutiaoMini) {
        const backUrl = encodeURIComponent(`${window.location.origin}/sole/member/pay-result`);
        // 头条小程序环境，走头条小程序支付流程
        invokeToutiaoPay(prepayRes, orderNumber, backUrl);
        return;
    }
};

/**
 * 商城支付方法整合为一个，根据环境自动选择支付方式
 * @param {Object} prepayRes 支付接口返回参数
 * @param {String} orderNumber 订单号
 * @param {Boolean} isCodeMode 是否是取餐模式
 */
export const autoShopPayment = (prepayRes, orderNumber, callback) => {
    const { isWechatMini, isAlipay, isToutiaoMini } = platformTruth();
    if (isWechatMini) {
        const backUrl = encodeURIComponent(`${window.location.origin}/sole/shop-order/list`);
        // 小程序环境，走小程序支付流程
        invokeWechatMiniShopPay(prepayRes, orderNumber, backUrl, true);
        return;
    }
    if (isAlipay) {
        invokeAliPay(prepayRes, orderNumber, callback);
        return;
    }
    if (isToutiaoMini) {
        const backUrl = encodeURIComponent(`${window.location.origin}/sole/shop-order/list`);
        // 头条小程序环境，走头条小程序支付流程
        invokeToutiaoPay(prepayRes, orderNumber, backUrl);
        return;
    }
};

/**
 * 发送信息给小程序
 * @param {Object} info 信息
 */
export const sendMessageToMini = (info) => {
    const { isAlipay, isToutiaoMini } = platformTruth();
    if (isAlipay) {
        window.my && window.my.postMessage({
            ...info,
        });
    }
    if (isToutiaoMini) {
        window.tt && window.tt.miniProgram.postMessage({
            ...info,
        });
    }
};

/**
 * 添加监听事件，头条小程序直接跳回首页
 */
export const backMiniIndex = () => {
    const { isToutiaoMini } = platformTruth();
    window.onhashchange = () => {
        if (isToutiaoMini) {
            window.tt.miniProgram.navigateBack();
        }
    };
};
